<?php


namespace App\Services;


use Illuminate\Http\Request;

class DataVerify
{
    /**
     * 获取百度开放平台的票据
     * 参考链接：https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
     */
    public function getAccessToken($ApiKey = '', $SecretKey = '', $grantType = 'client_credentials')
    {

        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type'] = $grantType;
        $post_data['client_id'] = $ApiKey;
        $post_data['client_secret'] = $SecretKey;
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);

        $res = (new Curl)->postUrl($url, $post_data);
        if (isset($res['error'])) {
            exit('API Key或者Secret Key不正确');
        }
        $accessToken = $res['access_token'];
        return $accessToken;
    }

    /**
     * 内容审核
     */
    public function contentAudit(Request $request)
    {
        $content = $request->post('content');
        $token = $this->getAccessToken(config('baiduyun.ApiKey'), config('baiduyun.SecretKey'));

        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token;
        $bodys = array(
            'text' => $content
        );
        $verifyInfo = (new Curl())->postUrl($url,$bodys);
        //结果转成数组
        $articleInfo = json_decode($verifyInfo, true);
        //根据自己的业务逻辑进行处理
        return $articleInfo;
    }

    /**
     * 图片审核
     */
    public function imageAudit($fileTmp)
    {
        $token = $this->getAccessToken(config('baiduyun.ApiKey'), config('baiduyun.SecretKey'));
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=' . $token;
        $img = file_get_contents($fileTmp);//本地路径
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img
        );
        $verifyInfo = (new Curl())->postUrl($url, $bodys);
        return $verifyInfo;
    }

}
